package top.yxqz.session.demo.test;

import top.yxqz.session.demo.school.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mr.余
 * @date 2022/11/28
 * @package top.yxqz.session.demo.test
 * 页面：登录成功后的首页
 */
@WebServlet("/index")
public class indexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

//        判断用户是否已经登录
        HttpSession session = request.getSession(); //得到当前请求的session会话
        Student stu = (Student) session.getAttribute("stu");//得到session会话域中的数据

        if (stu==null){
//            没有登录
            System.out.println("用户没有登录，直接访问了首页");
//            重定向到登录页面
            response.sendRedirect(getServletContext().getContextPath()+"/stulogin");
        }else {
//            已经登录了
            System.out.println("用户已经成功登录了");
            writer.println("欢迎你：<h1>"+stu.getUserName()+"</h1>");
        }


    }
}
